/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.DeleteObjectiveCmd;
import com.itgrail.pilot.domain.user.service.ObjectiveKeyResultService;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.*;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.*;
import com.itgrail.pilot.infrastructure.tunnel.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.exception.BusinessException;

import static com.itgrail.pilot.domain.user.enums.PeriodStatusEnum.PERIOD_BEGIN;


@CmdHandler
public class DeleteObjectiveCmdExe implements CommandExecutorI<ResultData<Integer>, DeleteObjectiveCmd> {

    @Autowired
    private ObjectiveMapper mapper;

    @Autowired
    private ObjectiveKeyResultService service;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private OkrPeriodMapper periodMapper;

    @Autowired
    private DictTypeMapper dictTypeMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData execute(DeleteObjectiveCmd cmd) {
        ResultData resultData = ResultData.success(null);
        check(cmd);
        service.deleteOkr(cmd.getId());
        return resultData;
    }

    protected boolean check(DeleteObjectiveCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getId(), "id不能为null");

        ObjectiveDO objectiveDO = mapper.selectById(cmd.getId());
        if (objectiveDO == null) {
            throw new BusinessException("500", "没有查询到目标内容");
        }
        OkrPeriodDO okrPeriodDO = periodMapper.selectById(objectiveDO.getOkrPeriodId());
        if (objectiveDO == null) {
            throw new BusinessException("500", "没有查询到目标内容");
        }
        DictTypeDO dictTypeDO = dictTypeMapper.selectById(okrPeriodDO.getIsEdit());
        if (dictTypeDO == null) {
            throw new BusinessException("500", "没有查询到目标内容");
        }
        if (!dictTypeDO.getDictCode().equals(PERIOD_BEGIN.getCode())) {
            throw new BusinessException("500", "当前状态不能删除");
        }
        cmd.setCurrentUserId(SessionUtils.currentUserId());
        if (!isAuthDelete(objectiveDO, cmd.getCurrentUserId())) {
            throw new BusinessException("500", "无删除权限");
        }
        return true;
    }

    /**
     * 判断当前登录用户是否是超管或者创建人
     *
     * @param objectiveDO
     * @param currentUserId
     * @return
     */
    private boolean isAuthDelete(ObjectiveDO objectiveDO, Integer currentUserId) {
        boolean isDeleted = false;
        Integer created = objectiveDO.getCreated();
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", currentUserId);
        UserDO userDO = userMapper.selectOne(queryWrapper);
        if (null != userDO) {
            String account = userDO.getAccount();
            QueryWrapper<UserRolesDO> userRolesDOQueryWrapper = new QueryWrapper<>();
            userRolesDOQueryWrapper.eq("username", account);
            userRolesDOQueryWrapper.eq("role", "ADMIN");
            UserRolesDO userRolesDO = userRolesMapper.selectOne(userRolesDOQueryWrapper);
            if (null != userRolesDO || currentUserId.equals(created)) {
                isDeleted = true;
            }
        }
        return isDeleted;
    }

}
